<!-- metalPurchaseCommodityMgtPage.vue -->
<template>
    <div class="purchase-commodity-container">
        <el-row>
            <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
                <el-form :inline="true" :model="filter" class="demo-form-inline">

                    <el-form-item label="供应商">
                        <el-input v-model="filter.targetObjName" placeholder="供应商名称" clearable />
                    </el-form-item>

                    <el-form-item style="width: 300px" label="业务日期范围">
                        <el-date-picker v-model="dateRange" type="daterange" range-separator="~"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </el-form-item>

                    <el-form-item style="width: 300px">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                        <el-button icon="Refresh" @click="refreshList">刷新</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
                <el-table v-loading="loading" :data="dataList" style="width: 100%; min-width: 600px; height: 100%;">
                    <el-table-column label="日期" align="center">
                        <template #default="scope">
                            {{ formatDate(scope.row.operateDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="单号" align="center" width="180">
                        <template #default="scope">
                            {{ scope.row.orderId }}
                        </template>
                    </el-table-column>
                    <el-table-column label="客户" align="center">
                        <template #default="scope">
                            {{ scope.row.targetObjName || "" }}
                        </template>
                    </el-table-column>

                                <el-table-column label="品名" align="center">
                        <template #default="scope">
                            {{ scope.row.commodity.standard || "" }}
                        </template>
                    </el-table-column>


                    <el-table-column label="重量" align="center">
                        <template #default="scope">
                            {{ formatQuality(scope.row.count.value) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="成色" align="center">
                        <template #default="scope">
                            {{ metalFiness(scope.row?.discount?.value) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="折后重量" align="center">
                        <template #default="scope">
                            {{ getDiscountWeight(scope.row) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="单价(元/g)" align="center">
                        <template #default="scope">
                            {{
                                getPriceInfo(scope.row)
                            }}
                        </template>
                    </el-table-column>

                    <el-table-column label="应付金额" align="center">
                        <template #default="scope">
                            {{ getBatchPriceInfo(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="模式" align="center">
                        <template #default="scope">
                            {{ scope.row.metalPurchaseTradeMode?.name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" align="center">
                        <template #default="scope">
                            {{ scope.row.orderRemark }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>

        <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { PurchaseUiAction } from '../../public/engine/uiAction/purchaseUiAction'
import { DealOrderCommodityFilter } from '../../public/engine/sales/dealOrderCommodityFilter'
import { DataPage } from '../../public/network/communicationConverter'
import { DateUtil } from '../../public/utils/dateUtil'
import { Util } from '../../public/utils/util'
import EventBus from '../../public/engine/ipc/eventBus'
import { deletePurchaseNetworkCache } from '../../public/network/api'
import { MetalPurchaseTradeMode } from '../../public/engine/common/metalDefinition'

export default {
    name: 'metalPurchaseCommodityList',

    data() {
        return {
            loading: false,
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 20,
            },
            filter: new DealOrderCommodityFilter(),
            dateRange: [],
            dataList: [],
            purchaseUiAction: new PurchaseUiAction(),
        }
    },

    mounted() {
        this.getList()
        EventBus.on('purchaseCommodityUpdated', this.getList)
    },

    beforeUnmount() {
        EventBus.off('purchaseCommodityUpdated', this.getList)
    },

    computed: {

    },

    methods: {

        getPriceInfo(batch) {
            if (batch.metalPurchaseTradeMode) {
                if (batch.metalPurchaseTradeMode.code == MetalPurchaseTradeMode.SettleMetal.code) {
                    return ''
                }
            }

            return batch.singlePriceAfterTax.value

        },

        getBatchPriceInfo(batch) {
            if (batch.metalPurchaseTradeMode) {
                if (batch.metalPurchaseTradeMode.code == MetalPurchaseTradeMode.SettleMetal.code) {
                    return ''
                }
            }

            return batch.batchPriceWithTax.value

        },

        getDiscountWeight(batch) {
            if (batch.metalPurchaseTradeMode) {
                if (batch.metalPurchaseTradeMode.code == MetalPurchaseTradeMode.SettleMetal.code) {
                    return batch.countAfterDiscount.value
                }
            }

            return ""

        },

        metalFiness(value) {
            if (!value) {
                return '--';
            }

            // 成色系统是百分比，换为千分比
            let finessValue = value * 10;

            if (finessValue == 1000) {
                return '24K';
            }

            return finessValue;
        },
        refreshList() {
            deletePurchaseNetworkCache();
            this.getList()
        },
        async getList() {
            try {
                this.loading = true

                // Update filter with date range
                if (this.dateRange?.length === 2) {
                    this.filter.startDate = this.dateRange[0];
                    this.filter.endDate = new Date(this.dateRange[1])
                    this.filter.endDate.setHours(23, 59, 59, 999)
                } else {
                    this.filter.startDate = null
                    this.filter.endDate = null
                }

                const res = await this.purchaseUiAction.getPurchaseCommoditiesListByPage({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    filter: this.filter.toJson({ withState: true })
                })

                if (res?.data?.dataList) {
                    this.dataList = res.data.dataList
                    this.total = res.data.pageInfo?.total || res.data.dataList.length
                } else if (res?.resErr) {
                    ElMessage.error('获取采购商品列表失败: ' + res.resErr)
                }
            } catch (error) {
                console.error('获取采购商品列表失败', error)
                ElMessage.error('获取采购商品列表失败')
            } finally {
                this.loading = false
            }
        },

        handleSearch() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetSearch() {
            this.filter.clear()
            this.dateRange = []
            this.queryParams.pageNum = 1
            this.getList()
        },

        formatDate(dateStr) {
            if (!dateStr) return ''
            return DateUtil.formatDate(dateStr, "yyyy-MM-dd HH:mm")
        },

        formatCurrency(value) {
            return Util.getFundString(value)
        },

        formatQuality(value) {
            return Util.getCountString(value)
        }
    }
}
</script>

<style scoped>
.purchase-commodity-container {
    padding-top: 0px;
    padding-left: 20px;
}
</style>